package com.gzhryc.common.event;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 定时执行服务
 * @author 张浩
 * @version 1.0.0(2013-10-26)
 */
public class TimerHandleService {
	
	volatile static Integer index = 0;
	
	final static List<Timer> timers = new ArrayList<Timer>();
	
	static{
		//获取CPU内核数
		final int coresCount = Runtime.getRuntime().availableProcessors();
		for(int i=0;i<coresCount;i++){
			timers.add(new Timer(true));
		}
	}
	
	/**
	 * 安排延迟执行任务
	 * @param task	快速任务
	 * @param delay 执行延迟时间（微秒）
	 */
	public static void schedule(TimerTask task,long delay){
		int i = getIndex();
		synchronized(timers.get(i)){
			try{
				timers.get(i).schedule(task,delay);
			}catch(IllegalStateException e){
				timers.set(i, new Timer(true));
				timers.get(i).schedule(task,delay);
			}
		}
	}
	
	public static void schedule(TimerTask task,long delay,long period){
		int i = getIndex();
		synchronized(timers.get(i)){
			try{
				timers.get(i).schedule(task, delay, period);
			}catch(IllegalStateException e){
				timers.set(i, new Timer(true));
				timers.get(i).schedule(task, delay, period);
			}
		}
	}
	
	private static int getIndex(){
		synchronized(index){
			index = index + 1;
			if(index >= timers.size()){
				index = 0;
			}
		}
		return index;
	}

}
